package com.fjeld.middleware.activemq;

import com.fjeld.middleware.constants.PropertiesManager;
import com.fjeld.middleware.jaxb.ObjectFactory;
import com.fjeld.middleware.jaxb.V1Heartbeat;
import com.fjeld.middleware.util.serverstatus.ServerStatus;
import org.apache.log4j.Logger;

import javax.jms.JMSException;

/**
 * Created by IntelliJ IDEA.
 * User: fjeld
 * Date: 11/12/2011
 * Time: 17:15
 * <p/>
 * Publishing heartbeats at regular intervals
 */
public class HeartbeatPublisher extends TopicPublisher implements Runnable
{
    private static final Logger LOGGER = Logger.getLogger(HeartbeatPublisher.class);
    private int publishInterval;

    public HeartbeatPublisher(String topicString, String publisherName) throws JMSException
    {
        super(topicString, publisherName);
        LOGGER.info("HeartBeat publisher: " + publisherName);
        String publishIntervalString = PropertiesManager.getProperties().getProperty("Heartbeat.PublisherInterval", "1100");
        publishInterval = Integer.parseInt(publishIntervalString);
        if (publishInterval < 1000)
        {
            LOGGER.debug("Overrode publish interval to 1000 milliseconds from " + publishInterval + "(String property: " + publishIntervalString + ")");
            publishInterval = 1000;
        }
    }

    public void startConnection()
    {
        super.startConnection();
        new Thread(this).start();
    }

    public void run()
    {
        try
        {
            while (true)
            {
                V1Heartbeat v1Heartbeat = ObjectFactory.OBJECT_FACTORY.createV1Heartbeat();
                v1Heartbeat.setHostname(hostName);
                v1Heartbeat.setServername(publisherName);
                v1Heartbeat.setStatus(ServerStatus.Up.toString());
                publish(v1Heartbeat);
                Thread.sleep(publishInterval);
            }
        } catch (Exception e)
        {
            LOGGER.error(e);
        }
    }
}
